package br.com.unibratec.service;

import java.util.List;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import br.com.unibratec.negocio.Evento;
import br.com.unibratec.negocio.EventoDAO;
import br.com.unibratec.receiver.WidgetProvider;

public class WidgetService extends Service {

	private static List<Evento> eventos;
	private static int max;
	private static int cursor;
	private int appWidgetId;

	public static final String ACTION_NEXT = "next";
	public static final String ACTION_PREVIOUS = "prev";
	public static final String ACTION_LOAD_DATA = "load";
	public static final String ACTION_REFRESH_EVENTO = "refresh";
	public static final String ACTION_REMOVE_EVENTO = "remove";

	@Override
	public void onCreate() {
		super.onCreate();
		this.load(this);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		String acao = intent.getAction();
		this.appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
		this.tratarAcoes(acao, intent);
		return super.onStartCommand(intent, flags, startId);
	}

	private void send() {
		Intent it = new Intent(WidgetProvider.ACTION_UPDWIGET);
		if (max != 0) {
			it.putExtra("evento", this.getCurrentEvento());
		}
		it.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, this.appWidgetId);
		sendBroadcast(it);
	}

	private void tratarAcoes(String acao, Intent intent) {
		WidgetProvider.printLog("tratarAcoes:acao => " + acao);
		if (acao != null) {
			if (ACTION_NEXT.equals(acao)) {
				this.next();
				this.send();
			} else if (ACTION_PREVIOUS.equals(acao)) {
				this.previous();
				this.send();
			} else if (ACTION_LOAD_DATA.equals(acao)) {
				this.load(this);
			} else if (ACTION_REFRESH_EVENTO.equals(acao)) {
				this.load(this);
			} else if (ACTION_REMOVE_EVENTO.equals(acao)) {
				this.load(this);
			}
		}
	}

	private Evento getCurrentEvento() {
		return eventos.get(cursor);
	}

	private void next() {
		cursor++;
		if (cursor == max) {
			cursor = 0;
		}
	}

	private void previous() {
		cursor--;
		if (cursor < 0) {
			cursor = max - 1;
		}

	}

	public void load(Context context) {
		WidgetProvider.printLog("load");
		eventos = EventoDAO.getInstace(context).listar();
		cursor = 0;
		max = eventos.size();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
}
